# -*- coding: UTF-8 -*-
import sys
import os
import xlrd
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter


def get_base_price_table(filepath):
    pt = {}
    workbook = xlrd.open_workbook(filepath)
    sheet = workbook.sheet_by_index(0)
    count = sheet.nrows
    for index in range(0, count):
        row = sheet.row(index)
        print(row)
        pt[row[0].value] = row[1].value
    return pt


def set_detail_table(sheet, price_table, start_row_index):
    for row in range(start_row_index, sheet.max_row + 1):
        title = sheet.cell(row=row, column=1).value
        if price_table.keys().__contains__(title):
            sheet.cell(row=row, column=2, value=price_table[title])


def set_detail_file(price_table, filepath, start_row_index):
    workbook = load_workbook(filepath)
    for sheetname in workbook.get_sheet_names():
        set_detail_table(workbook.get_sheet_by_name(sheetname), price_table, start_row_index)
    workbook.save(filepath)


if __name__ == "__main__":
    print("dear uncle start now!")
    pt = {}
    if sys.argv.__len__() != 4:
        print("input parameter error")
        print("you should input base_price detail detail_start_row")
        print("exit")

    root = os.getcwd()
    print("root path: %s" % root)
    base_price_path = root + "/" + sys.argv[1]
    detail_path = root + "/" + sys.argv[2]
    start_row = sys.argv[3]
    pt = get_base_price_table(base_price_path)
    set_detail_file(pt, detail_path, int(start_row))
